package com.jwiki.app.jtoolkit.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import com.alibaba.fastjson.JSON;
import com.jwiki.app.jtoolkit.controller.data.Response;

public class ExceptionInterceptor extends SimpleMappingExceptionResolver {

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception ex) {
        boolean isSendAjax = (request.getHeader("X-Requested-With") != null
                && request.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest"));

        if (isSendAjax) {
            // ajax
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            try (PrintWriter writer = response.getWriter()) {
                Response data = new Response();
                data.setSuccess(false);
                data.setMessage(ex.getMessage());
                writer.write(JSON.toJSONString(data));
                writer.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return new ModelAndView();
        } else {
            // redirect
            return super.doResolveException(request, response, handler, ex);
        }
    }

}
